package com.chiry.business.controller;

import com.alibaba.nacos.api.cmdb.spi.CmdbService;
import com.chiry.business.entity.Result;
import com.chiry.business.until.command.CMDUtil;
import com.chiry.business.until.command.SysApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.listener.LoggingErrorHandler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.util.concurrent.*;

/**
 * @author fyx
 * @version 1.0
 * @date 2021/8/12 17:55
 */
@RestController
@RequestMapping("/model")
public class ModelSwitchController {
    final static Logger logger = LoggerFactory.getLogger(ModelSwitchController.class);
    //cmd /c conda activate my_paddlex && hub serving start --modules insectDetection==1.0 --port 8866
    final static String COMMAD_START = "cmd /c conda activate my_paddlex && hub serving start --modules ";
    //cmd /c conda activate my_paddlex && hub serving stop --port 8866
    final static String COMMAD_STOP = "cmd /c conda activate my_paddlex && hub serving stop --port ";
    @Value("${custom.config.name}")
    String name;

    @Autowired
    @Qualifier(value = "customizeThreadPool")
    Executor CustomizeThreadPool;

    @RequestMapping("/start")
    public Result<String> startModelRequest(@RequestParam("modelName") String modelName, @RequestParam("version") String version, @RequestParam("port") String port) throws ExecutionException, InterruptedException {
        FutureTask<Result> resultFutureTask = new FutureTask<>(new Callable<Result>() {
            @Override
            public Result call() throws Exception {
                Runtime runtime = Runtime.getRuntime();
                Result<String> result = null;
                try {
                    String cmd = COMMAD_START + modelName + "==" + version + " --port " + port;
                    String res = CMDUtil.excuteCMDCommand(cmd);
                    result = new Result<String>(200, "success", "execute command success");
                    logger.info(result.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    result = new Result<String>(500, "error", "can not execute system's command");
                    logger.error(result.toString());
                    e.printStackTrace();
                }
                return result;
            }
        });
        CustomizeThreadPool.execute(resultFutureTask);
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info(addr.getHostAddress());
        Result<String> resu = new Result<>(200, "success","http://"+addr.getHostAddress()+":"+port+"/predict/"+ modelName);
        logger.info("http://"+addr.getHostAddress()+":"+port+"/predict/"+ modelName);
        return resu;
    }

    @RequestMapping("/stop")
    public Result<String> stopModelRequest(@RequestParam("port") String port) {

        Runtime runtime = Runtime.getRuntime();
        Result<String> result = null;
        try {
            String cmd = COMMAD_STOP+port;
            String res = CMDUtil.excuteCMDCommand(cmd);
            System.out.println(res);
            result = new Result<String>(200, "success", "The model has been closed!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            result = new Result<String>(500, "error", "can not execute system command");
            e.printStackTrace();
        }
        return result;

    }

}
